<?php
session_start();
require_once '../config/database.php';

if (!is_admin()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (isset($_POST['brand_id']) && isset($_POST['model_name'])) {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if model already exists
    $check_query = "SELECT id FROM models WHERE LOWER(name) = LOWER(?) AND brand_id = ?";
    $check_stmt = $db->prepare($check_query);
    $check_stmt->execute([trim($_POST['model_name']), $_POST['brand_id']]);
    
    if ($existing = $check_stmt->fetch()) {
        echo json_encode(['success' => true, 'model_id' => $existing['id']]);
        exit;
    }
    
    // Add new model
    $query = "INSERT INTO models (brand_id, name) VALUES (?, ?)";
    $stmt = $db->prepare($query);
    
    if ($stmt->execute([$_POST['brand_id'], trim($_POST['model_name'])])) {
        echo json_encode([
            'success' => true,
            'model_id' => $db->lastInsertId()
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add model']);
    }
} 